const std = @import("std");
const cz = @import("cz-runtime");

const CounterMsg = union(enum) {
    increment,
    decrement,
    get: *u32,
    stop,
};

const CounterActor = cz.Actor(u32, CounterMsg);

fn counterHandler(actor: *CounterActor, msg: CounterMsg) !void {
    switch (msg) {
        .increment => {
            actor.state += 1;
            std.debug.print("Counter: {d}\n", .{actor.state});
        },
        .decrement => {
            actor.state -= 1;
            std.debug.print("Counter: {d}\n", .{actor.state});
        },
        .get => |result_ptr| {
            result_ptr.* = actor.state;
        },
        .stop => {
            actor.stop();
        },
    }
}

pub fn main() !void {
    std.debug.print("=== Cz Language - Counter Example ===\n\n", .{});
    
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    
    const alloc = gpa.allocator();
    
    // 创建 Actor 系统
    var system = cz.ActorSystem.init(alloc);
    
    // 创建 Counter Actor，初始值为 0
    std.debug.print("Creating counter actor...\n", .{});
    var counter = try system.spawn(u32, CounterMsg, 0);
    defer counter.deinit(alloc);
    
    // 启动 Actor
    try counter.start(&counterHandler);
    
    // 发送消息
    std.debug.print("Sending increment messages...\n", .{});
    try counter.send(.increment);
    try counter.send(.increment);
    try counter.send(.increment);
    
    std.Thread.sleep(100_000_000); // 等待 100ms
    
    std.debug.print("Sending decrement message...\n", .{});
    try counter.send(.decrement);
    
    std.Thread.sleep(100_000_000);
    
    // 获取当前值
    var result: u32 = 0;
    try counter.send(.{ .get = &result });
    
    std.Thread.sleep(100_000_000);
    
    std.debug.print("\nFinal counter value: {d}\n", .{result});
    
    // 停止 Actor
    try counter.send(.stop);
    std.Thread.sleep(50_000_000);
    
    std.debug.print("\n=== Example completed ===\n", .{});
}
